﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.DeepProcess;
using Provenance.Infra.Repositories.DeepProcess;
using Provenance.Write.Api.Application.Command.DeepProcess;

namespace Provenance.Write.Api.Application.CommandHandler.DeepProcess
{
    public class UpPackagingMaterialCommandHandler : IRequestHandler<UpPackagingMaterialCommand, ApiResult>
    {
        private readonly IPackagingMaterialRepository _packageMaterialRepository;
        private readonly ILogger<UpPackagingMaterialCommandHandler> _logger;
        private readonly IMapper _mapper;
        public UpPackagingMaterialCommandHandler(IPackagingMaterialRepository packageMaterialRepository, ILogger<UpPackagingMaterialCommandHandler> logger, IMapper mapper)
        {
            _packageMaterialRepository = packageMaterialRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpPackagingMaterialCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _packageMaterialRepository.GetAsync(x => x.PackagingMaterialId == request.PackagingMaterialId);
                obj = _mapper.Map(request, obj);
                await _packageMaterialRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error updating packaging material: " + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
